package com.zp.oauth2.gateway.init;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zp.common.base.constant.Atom;
import com.zp.common.base.dao.AuthRepository;
import com.zp.common.base.dao.RoleRepository;
import com.zp.common.base.entity.AuthInfo;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

import static com.zp.common.base.constant.Atom.CONSTANT_ONE;

/**
 * 初始化加载所有权限
 *
 * @author zp
 */
@Component
public class LoadPermissionService implements InitializingBean {
    @Resource
    private AuthRepository authRepository;
    @Resource
    private RoleRepository roleRepository;
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public void afterPropertiesSet() throws Exception {
        QueryWrapper<AuthInfo> authInfoQueryWrapper=new QueryWrapper<>();
        authInfoQueryWrapper.eq("status",CONSTANT_ONE);
        //拿到所有的权限列表
        List<AuthInfo> authInfos = authRepository.selectList(authInfoQueryWrapper);
        authInfos
                .forEach(x -> {
                    List<String> roles = roleRepository.loadRoleByAuthInfoId(x.getId());
                    if (CollUtil.isNotEmpty(roles)) {
                        redisTemplate.opsForHash().put(Atom.OAUTH_URLS, x.getUrl(), roles);
                    }
                });

    }
}
